package gr.atc.epart;

import gr.atc.epart.actions.Action.Type;
import gr.atc.epart.net.ActionsPage.SortBy;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddCategoryActivity extends Activity {
	static final int TIME_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID_TO = 1;
	static final int DATE_DIALOG_ID_FROM = 2;

	int YearTo = 2010, monthTo = 0, dayTo = 1, YearFrom = 2010, monthFrom = 0,
			dayFrom = 1;

	EditText fromText = null;
	EditText toText = null;
	String text, creator;

	String[] tags;
	Spinner sortBySpinner;
	Date startDate, stopDate;
	SortBy sortBy;
	Type actionType;
	String sortByString;
	String typeString;

	private CustomCategoriesManager _categoryManager;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.addcategory);

		Calendar current = Calendar.getInstance();
		dayFrom = current.get(Calendar.DAY_OF_MONTH);
		dayTo = current.get(Calendar.DAY_OF_MONTH);

		monthFrom = current.get(Calendar.MONTH);
		monthTo = current.get(Calendar.MONTH);

		YearFrom = current.get(Calendar.YEAR);
		YearTo = current.get(Calendar.YEAR);

		Button fromButton = (Button) findViewById(R.id.categoryfrombutton);
		fromButton.setOnClickListener(fromBtnListener);

		Button toButton = (Button) findViewById(R.id.categorytobutton);
		toButton.setOnClickListener(fromBtnListener);

		Button createButton = (Button) findViewById(R.id.categorycreatebutton);
		createButton.setOnClickListener(createBtnListener);

		fromText = (EditText) findViewById(R.id.categoryfrom);
		toText = (EditText) findViewById(R.id.categoryto);

		sortBySpinner = (Spinner) findViewById(R.id.categorysortbyspinner);
		Spinner typeSpinner = (Spinner) findViewById(R.id.categorytypespinner);

		ArrayAdapter<String> sortByAttributes = new ArrayAdapter<String>(this,
				R.layout.sortbyspinnerview, getResources().getStringArray(
						R.array.sortBy));

		ArrayAdapter<String> typeAttributes = new ArrayAdapter<String>(this,
				R.layout.sortbyspinnerview, getResources().getStringArray(
						R.array.type));

		sortBySpinner.setAdapter(sortByAttributes);
		typeSpinner.setAdapter(typeAttributes);

		sortBySpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						sortByString = item.toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		typeSpinner
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int pos, long id) {
						Object item = parent.getItemAtPosition(pos);
						typeString = item.toString();
					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});
		_categoryManager = new CustomCategoriesManager(this);

	}

	private OnClickListener createBtnListener = new OnClickListener() {
		String msg = "";

		public void onClick(View v) {
			
			if (v == findViewById(R.id.categorycreatebutton)) {

				String fromString = fromText.getText().toString();
				String toString = toText.getText().toString();
				EditText nameTxtEdit = (EditText) findViewById(R.id.categoryname);
				String nameString = nameTxtEdit.getText().toString();

				EditText tagsTxtEdit = (EditText) findViewById(R.id.categorytags);
				String tagsString = tagsTxtEdit.getText().toString();
				EditText creatorTxt = (EditText) findViewById(R.id.categorycreator);
				String creatorString = creatorTxt.getText().toString();

				Type type = Type.valueOf(typeString);

				boolean valid = true;

				if (nameString.equals("")) {
					msg = "Category name cannot be empty";
					valid = false;
				} else {

					if (!fromString.equals("") && !toString.equals("")) {

						SimpleDateFormat formatter = new SimpleDateFormat(
								"dd-MM-yyyy");

						try {

							Date startDate = formatter.parse(fromString);
							Date endDate = formatter.parse(toString);

							if (startDate.after(endDate)
									|| startDate.equals(endDate)) {
								valid = false;
								msg = "Start Date must be earlier than Stop Date";
							}

						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}

				if (creatorString.equals("")) {
					creatorString = "all";
				}

				if (valid) {
					if (_categoryManager.existsTab(nameString)) {
						createAlertFailure("The category allready exists");
					} else {

						if (_categoryManager.addCustomTab(nameString, type,
								creatorString, fromString, toString,
								tagsString, SortBy.Popularity, 1, 50)) {
							createAlertSuccess();
						} else {
							createAlertFailure("Could not create category");
						}
					}
				} else {
					createAlertFailure(msg);
				}

			}
		}

	};

	private OnClickListener fromBtnListener = new OnClickListener() {
		public void onClick(View v) {
			if (v == findViewById(R.id.categoryfrombutton)) {
				showDialog(DATE_DIALOG_ID_FROM);
			} else if (v == findViewById(R.id.categorytobutton)) {
				showDialog(DATE_DIALOG_ID_TO);
			} else if (v == findViewById(R.id.categoryfrom)) {
				showDialog(DATE_DIALOG_ID_FROM);
			}
		}

	};

	private DialogInterface.OnClickListener okButtonListener = new DialogInterface.OnClickListener() {

		public void onClick(DialogInterface dialog, int which) {
			setResult(200);
			finish();
		}

	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID_TO:
			return new DatePickerDialog(this, mDateSetListener, YearTo,
					monthTo, dayTo);
		case DATE_DIALOG_ID_FROM:
			return new DatePickerDialog(this, mDateSetListenerFrom, YearFrom,
					monthFrom, dayFrom);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			YearTo = year;
			monthTo = monthOfYear;
			dayTo = dayOfMonth;

			toText.setText(dayTo + "-" + (monthTo + 1) + "-" + YearTo);
			/*
			Toast.makeText(
					getBaseContext(),
					"You have selected : " + dayTo + "-" + (monthTo + 1) + "-"
							+ YearTo, Toast.LENGTH_SHORT).show();
			*/				
		}

	};

	private DatePickerDialog.OnDateSetListener mDateSetListenerFrom = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			YearFrom = year;
			monthFrom = monthOfYear;
			dayFrom = dayOfMonth;

			fromText.setText(dayFrom + "-" + (monthFrom + 1) + "-" + YearFrom);
			/*
			Toast.makeText(
					getBaseContext(),
					"You have selected : " + dayFrom + "-" + (monthFrom + 1)
							+ "-" + YearFrom, Toast.LENGTH_SHORT).show();
			*/
		}

	};

	public void createAlertSuccess() {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage("New Category Created");
		dlgAlert.setTitle("Congratulations");
		dlgAlert.setPositiveButton("OK", okButtonListener);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

	public void createAlertFailure(String msg) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(msg);
		dlgAlert.setTitle("Failure");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

	public void createAlert() {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert
				.setMessage("Wrong date format: Please set the date as day/month/year");
		dlgAlert.setTitle("Error");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

}
